import {Response} from 'express';
import {Code, CodeMessage, codeType} from '../constants/code';
import logger from './logger';

interface ResOption {
    success?: boolean;
    type?: codeType;
    code?: number; // 改为 code
    message?: string;
}

class CommonResponse {
    private res: Response;

    constructor(res: Response) {
        this.res = res;
    }

    // 成功响应
    public send(data: unknown, options: ResOption = {}) {
        const resOptions = this.createOptions({
            type: 'success',
            message: CodeMessage['success'],
            success: true,
            ...options,
        });

        return this.respond(data, resOptions);
    }

    public success(data: unknown, message?: string, code?: number) {
        const resOptions = this.createOptions({
            success: true,
            type: 'success',
            message: message || CodeMessage['success'],
            code: code ?? 200, // 使用 code 代替 status
        });

        return this.respond(data, resOptions);
    }

    // 错误响应
    public error(data: unknown, message?: string, code?: number) {
        logger.error(message || CodeMessage['error']);
        const resOptions = this.createOptions({
            success: false,
            type: 'error',
            message: message || CodeMessage['error'],
            code: code ?? 400, // 使用 code 代替 status
        });

        return this.respond(data, resOptions);
    }

    // 无权限响应
    public denied(data: unknown, message?: string) {
        const resOptions = this.createOptions({
            success: false,
            type: 'denied',
            message: message || CodeMessage['denied'],
            code: 401, // 使用 code 代替 status
        });

        return this.respond(data, resOptions);
    }

    // 创建响应选项
    private createOptions(options: ResOption): ResOption {
        return {
            type: options.type ?? 'success',
            success: options.success ?? false,
            code: options.code, // 使用 code
            message: options.message ?? CodeMessage[options.type ?? 'success'],
        };
    }

    // 通用响应方法
    private respond(data: unknown, options: ResOption) {
        const {type, code, message, success} = options;
        const resCode = code ?? (success ? 200 : 409); // 使用 code

        const sendRes = {
            code: Code[type],
            data,
            success,
            ...(message && {message}), // 如果有 message 就附加到响应中
        };

        this.res.send(sendRes); // 设置状态码
    }
}

export default CommonResponse;
